package com.xiaoc.bulldozer.common.service.impl;

import com.xc.framework.common.base.ResponseCode;
import com.xc.framework.common.exception.BusinessException;
import com.xiaoc.bulldozer.common.dao.UserMapper;
import com.xiaoc.bulldozer.common.model.User;
import com.xiaoc.bulldozer.common.service.UserService;
import com.xiaoc.bulldozer.common.dto.UserDto;
import com.xiaoc.bulldozer.common.util.SecurityUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User Service 实现类
 * 
 * @author CodeGenerator
 * 
 * @date 2014-05-20 17:26:51
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User getUserById(Integer userId) {
        return userMapper.getUserById(userId);
    }
    
	@Override
	public User getUserByLoginName(String loginName) {
		return userMapper.getUserByLoginName(loginName);
	}

    @Override
    public void createUser(User user) {

        // 判断login name是否已经重复
        User existUser = userMapper.getUserByLoginName(user.getLoginName());
        if (existUser != null) {
            throw new BusinessException(ResponseCode.INTERNAL_ERROR, "登录名已经存在");
        }
        
        user.setLoginPwd(user.getLoginPwd());
        Long currentTime = System.currentTimeMillis();
        user.setCreateTime(currentTime);
        user.setUpdateTime(currentTime);
        user.setEnableStatus(User.STATUS_ENABLE);
        
        userMapper.create(user);
    }

    @Override
    public void updateUser(User user) {

        User existUser = populateUser(user);

        if (!StringUtils.equals(User.DEFAULT_PASSWORD, user.getLoginPwd())) {
            if (!user.getLoginPwd().matches(User.PASSWORD_REGEX)) {
                throw new BusinessException(ResponseCode.INTERNAL_ERROR, User.PASSWORD_VALID_MSG);
            }
            
        	existUser.setLoginPwd(SecurityUtils.generatePassword(user.getLoginPwd()));
        }

        userMapper.update(existUser);
    }

    private User populateUser(User user) {

        // 如果登陆名称已与其他登陆重复，则抛出异常
        User duplicateUser = userMapper.getUserByLoginName(user.getLoginName());
        if (!(duplicateUser == null || duplicateUser.getId().equals(user.getId()))) {
            throw new BusinessException(ResponseCode.INTERNAL_ERROR, "login name duplicated");
        }

        // 验证待修改的用户是否存在
        User existUser = userMapper.getUserById(user.getId());
        if (existUser == null) {
            throw new BusinessException(ResponseCode.INTERNAL_ERROR, "user not found");
        }

        // 判断用户是启用状态
        if (!existUser.isEnable()) {
            throw new BusinessException(ResponseCode.INTERNAL_ERROR, "user is disabled");
        }

        existUser.setLoginName(user.getLoginName());
        existUser.setName(user.getName());
        existUser.setUpdateTime(System.currentTimeMillis());
        existUser.setEnableStatus(user.getEnableStatus());

        return existUser;
    }

    @Override
    public void deleteUser(int userId) {

        User existUser = userMapper.getUserById(userId);

        // 判断用户是否存在
        if (existUser == null) {
            throw new BusinessException(ResponseCode.INTERNAL_ERROR, "user not found");
        }

        existUser.setEnableStatus(User.STATUS_DISABLE);
        userMapper.update(existUser);
    }

    @Override
    public void updatePassword(User user) {

        User existUser = userMapper.getUserById(user.getId());
        if (existUser == null) {
            throw new BusinessException(ResponseCode.INTERNAL_ERROR, "user not found");
        }
        
        existUser.setLoginPwd(user.getLoginPwd());
        userMapper.update(existUser);
    }
    
    @Override
    public void updateLockState(User user) {
        
        User existUser = userMapper.getUserById(user.getId());
        if (existUser == null) {
            throw new BusinessException(ResponseCode.INTERNAL_ERROR, "user not found");
        }

        existUser.setEnableStatus(user.getEnableStatus());
        userMapper.update(existUser);
    }

	@Override
	public Integer queryUserCount(UserDto userDto) {
		return userMapper.queryUserCount(userDto);
	}

	@Override
	public List<UserDto> queryUserList(UserDto userDto) {
		return userMapper.queryUserList(userDto);
	}

    @Override
    public List<User> getUserListByUserIdList(List<Integer> userIdList) {
        return userMapper.getUserListByUserIdList(userIdList);
    }

    @Override
    public Map<Integer, User> getUserMapByUserIdList(List<Integer> userIdList) {
        
        if (CollectionUtils.isEmpty(userIdList)) {
            return Collections.EMPTY_MAP;
        }
        
        Map<Integer, User> userMap = new HashMap<Integer, User>();
        List<User> userList = getUserListByUserIdList(userIdList);
        for (User user : userList) {
            userMap.put(user.getId(), user);
        }
        
        return userMap;
    }

}
